package com.veeder.datacollection.rs232.response.handler;


import com.veeder.datacollection.exception.SyntaxException;
import com.veeder.datacollection.rs232.response.HeightVolumePair;
import com.veeder.datacollection.rs232.response.TankChart;
import com.veeder.datacollection.rs232.response.TankResponseReport;
import com.veeder.datacollection.util.DateUtil;

public class RSA31RspHandler extends CmdRspParser {
	@Override
	public TankResponseReport<TankChart> parseCoreResponse(String coreResponse) throws SyntaxException {
		TankResponseReport<TankChart> result = null;
		try {
			result = new TankResponseReport<TankChart>();
			int position = 6;
			result.setTlsSysDate(
					DateUtil.convertToDate(coreResponse.substring(position, position += 10), DateUtil.DateFormat1));
			
			while (position < coreResponse.length() - 1) {
				TankChart chart = new TankChart();
				int tankId = Integer.parseInt(coreResponse.substring(position, position += 2));
				int pointsCount = Integer.parseInt(coreResponse.substring(position, position += 4), 16);
				for (int i = 0; i < pointsCount; i++) {
					String heightStr = coreResponse.substring(position, position += 16);
					double height = Double.longBitsToDouble(Long.parseLong(ASCIIHEX(heightStr), 16));
					String volStr = coreResponse.substring(position, position += 16);
					double volume = Double.longBitsToDouble(Long.parseLong(ASCIIHEX(volStr), 16));
					chart.addHVPair(new HeightVolumePair(height, volume));
				}
				result.setTankReponse(tankId, chart);
			}
		} catch (Exception e) {
			throw new SyntaxException(e.toString());
		}

		return result;
	}

	private static String ASCIIHEX(String src) {
		StringBuilder builder = new StringBuilder();
		for (int i = (src.length() / 2 - 1); i >= 0; i--) {
			builder.append(src.substring(2 * i, 2 * i + 2));
		}
		return builder.toString();
	}
	
}
